<?php
/**  
* CacheableModule.php
* 
* p.307
*/

class CacheableModule extends Module
{
   protected $cache_ttl;
   protected $cache_clr;

   public function __construct(Page &$page)
   {
      parent::__construct($page);

      $this->cache_ttl = 3600*10;  // 10시간 캐시
      $this->cache_clr = false;
   }

   public function create()
   {
      $cache_key = $this->get_cache_key();
      $cache_val = apc_fetch($cache_key);

      $hash = get_cache_hash($this->get_cache_vars());

      if (!$this->cache_clr && $cache_val && $cache_val["hash"] == $hash)
      {
         fetch_from_cache($cache_val["data"]);
      }
      else
      {
         store_into_cache($cache_key, $hash);
      }
   }

   public function set_cache_ttl($ttl)
   {
      $this->cache_ttl = $ttl;
   }

   public function set_cache_clr()
   {
      $this->cache_clr = true;
   }

   protected function get_cache_vars()
   {
      return microtime();
   }

   protected function fetch_from_cache($data)
   {
      $this->page->add_to_css_linked($data["css_linked"]);
      $this->page->add_to_css($data["css"]);

      $this->page->add_to_js_linked($data["js_linked"]);
      $this->page->add_to_js($data["js"]);

      return $data["content"];
   }

   protected function store_into_cache($cache_key, $hash)
   {
      $css_linked = $this->get_css_linked();
      $css = $this->get_css();

      $js_linked = $this->get_js_linked();
      $js = $this->get_js();

      $content = $this->get_content();

      $cache_val = array
      (
         "hash" => $hash,
         "data" => array
         (
            "css_linked" => $css_linked,
            "css"        => $css,
            "js_linked"  => $css_linked,
            "js"         => $js,
            "content"    => $content
         )
      );

      apc_store($cache_key, $cache_val, $this->cache_ttl);

      $this->page->add_to_css_linked($css_linked);
      $this->page->add_to_css($css);

      $this->page->add_to_js_linked($js_linked);
      $this->page->add_to_js($js);

      return $content;
   }

   protected function get_cache_hash($var)
   {
      return md5($var);
   }

   protected function get_cache_key()
   {
      return get_class($this);
   }
}
?>